package com.db.industry.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.db.core.utils.SnowflakeIdGenerator;
import com.db.core.vo.PageResult;
import com.db.core.vo.R;
import com.db.industry.dto.IndustryPageDto;
import com.db.industry.entity.Industry;
import com.db.industry.mapper.IndustryMapper;
import com.db.industry.service.IndustryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * <p>
 * 行业表 服务实现类
 * </p>
 *
 * @author db
 * @since 2023-10-29
 */
@Service
public class IndustryServiceImpl extends ServiceImpl<IndustryMapper, Industry> implements IndustryService {

    @Override
    public PageResult pageList(IndustryPageDto industryPageDto) {
        //设置分页信息
        IPage iPage = new Page();
        iPage.setCurrent(industryPageDto.getNow());
        iPage.setSize(industryPageDto.getSize());
        //设置查询过滤条件
        QueryWrapper<Industry> industryQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(industryPageDto.getName()))
            industryQueryWrapper.like("name",industryPageDto.getName());
        //开始查询
        IPage iPage1 = baseMapper.selectPage(iPage, industryQueryWrapper);
        //将数据封装到pageBean
        PageResult<Industry> pageResult = new PageResult<>();
        pageResult.setTotal(iPage1.getTotal());
        pageResult.setPages(iPage1.getPages());
        pageResult.setList(iPage1.getRecords());
        return pageResult;
    }

    @Transactional
    @Override
    public R insert(Industry industry) {
        Industry industry1 = baseMapper.selectOne(new QueryWrapper<Industry>().eq("name", industry.getName()));
        if (!StringUtils.isEmpty(industry1))
            return R.fail("添加失败，已存在相同行业");
        industry.setId(SnowflakeIdGenerator.nextIdAsString());
        industry.setCreateTime(new Date());
        baseMapper.insert(industry);
        return R.ok("添加成功");
    }

    @Transactional
    @Override
    public R update(Industry industry) {
        baseMapper.updateById(industry);
        return R.ok("保存成功");
    }
}
